<template>
	<view class="container">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="rgba(0,0,0,0.4)" leftWidth="90rpx" rightWidth="90rpx" color="#000" :fixed="true" :padding="false" :border="false" @clickLeft="$goBack(1)">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhb.png" mode="aspectFit"></image>
			</template>
			<text class="title"></text>
			<template slot="right">
			</template>
		</uni-nav-bar>
		<view class="video-box flex-r ac jc" v-if="videoFullPath">
			<video
				:id="videoId" 
				class="video" 
				object-fit="cover"
				:style="{width, height}"
				:src="videoFullPath" 
				:loop="true"
				:autoplay="true"
				:page-gesture="true" 
				:initial-time="initial"
				@pause="state = 0"
				@timeupdate="timeupdate"
				@error="videoError"
				@loadedmetadata="videoLoad"
				controls
			></video>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				videoId: '', //视频ID
				videoFullPath: '', //视频路径
				VideoContext: {}, //视频对象
				state: false, //播放状态
				initial: 0, //初始播放进度
				currentTime: 0, //当前播放时间
				
				height: '500rpx', //视频高度
				width: '750rpx', //视频宽度
			}
		},
		onLoad() {
			console.log(this.$Route.query);
			//生产视频ID，创建播放对象
			this.videoId = Date.now() + Math.ceil(Math.random()*10000000) + "";
			this.VideoContext = uni.createVideoContext(this.videoId);
			//获取播放链接路径
			let {aid, path} = this.$Route.query
			if(aid && path){
				this.articleId = aid
				this.videoPath = path
				this.initial = sessionStorage.getItem(path)
				this.videoFullPath = path.includes('http') ? path : this.$store.state.videoDomain + '/' + path
				this.state = true
			}else{
				this.state = false
			}
		},
		beforeRouteLeave(to, from, next) {
			//记录播放进度
			sessionStorage.setItem(this.videoPath, this.currentTime)
			next();
		},
		watch: {
			state(state, oldValue) {//切换播状态
				if(!state){
					this.VideoContext.pause()
				}else{
					if(!this.isError){
						this.VideoContext.play()
					}else{
						uni.showToast({
							title: '当前视频无法播放',
							icon: 'none'
						})
					}
				}
			},
		},
		methods: {
			//视频元数据加载完成
			videoLoad(event) {
				console.log(event);
				this.isError = false
				if(event.detail.height && event.detail.width){
					if(event.detail.height > event.detail.width){
						this.height = event.detail.height + 'px'
					}
				}
				this.VideoContext.play()
				this.VideoContext.seek(this.initial)
			},
			//视频加载错误回调
			videoError() {
				this.isError = true
			},
			//播放进度更新回调
			timeupdate(event){
				this.currentTime = event.detail.currentTime
			}
		}
	}
</script>

<style lang="scss">
	.container{
		width: 100%;
		height: var(--safe-height);
		background-color: #000000;
		.video-box{
			padding: 20rpx 0 40rpx;
			width: 100%;
			height: calc(var(--safe-height) - #{$navbar-height});
			box-sizing: border-box;
			.video{
				width: 100%;
				max-height: 100% !important;
			}
		}
	}
</style>
